package com.jiyi.activity.datainput.sm;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiyi.activity.datainput.DIBasePicActivity;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.datainput.new_input.BaseBuildBean;
import com.jiyi.bean.datainput.new_input.DataInputStreetBean;
import com.jiyi.bean.datainput.new_input.DataInputZoneBean;
import com.jiyi.exception.SampleProgressObserver;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.retrofit.HttpMethods;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.base.AppMediaType;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2018/3/21.
 */

public class BuildBaseInfoActivity extends DIBasePicActivity implements
        DownloadPicOverInterface {

    /* 头部 */
    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.etAdress)
    EditText etAdress;
    @BindView(R.id.etPropertyName)
    EditText etPropertyName;
    @BindView(R.id.etAQZRR)
    EditText etAQZRR;
    @BindView(R.id.etAQZRRTel)
    EditText etAQZRRTel;
    @BindView(R.id.etLXR)
    EditText etLXR;
    @BindView(R.id.etLXRTel)
    EditText etLXRTel;
    @BindView(R.id.etYWH)
    EditText etYWH;
    @BindView(R.id.etYWHZR)
    EditText etYWHZR;
    @BindView(R.id.etYWHZRTel)
    EditText etYWHZRTel;
    @BindView(R.id.etYWHLXR)
    EditText etYWHLXR;
    @BindView(R.id.etYWHLXRTel)
    EditText etYWHLXRTel;
    @BindView(R.id.etLouZhang)
    EditText etLouZhang;
    @BindView(R.id.etLouZhangTel)
    EditText etLouZhangTel;
    @BindView(R.id.isPass)
    RadioButton isPass;
    @BindView(R.id.isNoPass)
    RadioButton isNoPass;
    @BindView(R.id.rgIsPass)
    RadioGroup rgIsPass;
    @BindView(R.id.etWJWH)
    EditText etWJWH;


    @BindView(R.id.gvPic)
    GridView gvPic;

    int isPassValue = 0;


    String build_id = "";
    @BindView(R.id.etPolice)
    EditText etPolice;

    @BindView(R.id.spStreet)
    Spinner spStreet;
    @BindView(R.id.spZone)
    Spinner spZone;

    List<DataInputStreetBean> streetDataList = new ArrayList<DataInputStreetBean>();
    List<DataInputZoneBean> zoneDataList = new ArrayList<DataInputZoneBean>();

    CommonAdapter<DataInputStreetBean> stateFirstAdapter;
    CommonAdapter<DataInputZoneBean> stateSecondAdapter;

    String street,zone,firstZone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_build_base_info);
        ButterKnife.bind(this);
        init();
    }

    public void init() {
        getIntentData();
        setTop();
        setViewStatus();
        setAdapter();
        if (!TextUtils.isEmpty(build_id)) {
            //修改时，获取数据
            getData();
//            getFirst();
        } else {
            PicSelectConstans.publish_pics = new ArrayList<String>() {
            };
            refreshAdapter(gvPic);
            getFirst();
        }
        super.setDownloadPicOverInterface(this);


    }

    private void getIntentData() {
        build_id = getIntent().getStringExtra("build_no");
        if (TextUtils.isEmpty(build_id))
            build_id = "";
    }

    private void getData() {
        HttpMethods.getInstance().getBaseBuildInfo(UserInfoUtil.getCurrentUserAccessToken(), build_id, 2)
                .subscribe(new SampleProgressObserver<BaseBuildBean>(this) {
                    @Override
                    public void onNext(BaseBuildBean bean) {
                        if (TextUtils.isEmpty(bean.getId())) {
                            bean.setName("");
                            bean.setAddress("");
                            bean.setBuild_id("");
                            bean.setProperty_department("");
                            bean.setProperty_response_man("");
                            bean.setProperty_response_tel("");
                            bean.setProperty_contact_man("");
                            bean.setProperty_contact_tel("");
                            bean.setOwners_committee("");
                            bean.setCommittee_contact_man("");
                            bean.setCommittee_contact_tel("");
                            bean.setCommittee_response_man("");
                            bean.setCommittee_response_tel("");
                            bean.setCommittee_contact_man("");
                            bean.setCommittee_contact_tel("");
                            bean.setPeer_advisor("");
                            bean.setPeer_advisor_tel("");
                            bean.setIs_accept(0);
                            bean.setRecord_number("");
                            bean.setNo_edit(1);
                            bean.setStreet("");
                            bean.setCommunity("");
                            bean.setPolice_station("");
                        }

                        fillData(bean);
                    }
                });
    }

    private void fillData(BaseBuildBean baseBuildBean) {
        resetFirst();
        streetDataList.addAll(baseBuildBean.getStreet_list());
        firstZone = baseBuildBean.getCommunity();

        etName.setText(baseBuildBean.getName());
        etAdress.setText(baseBuildBean.getAddress());


        System.out.println("getPositionByStreetName(baseBuildBean.getStreet()):"  + getPositionByStreetName(baseBuildBean.getStreet()));
        System.out.println("getPositionByZoneName(baseBuildBean.getCommunity()):"  + getPositionByZoneName(baseBuildBean.getCommunity()));

        spStreet.setSelection(getPositionByStreetName(baseBuildBean.getStreet()),true);
        spZone.setSelection(getPositionByZoneName(baseBuildBean.getCommunity()),true);

        etPolice.setText(baseBuildBean.getPolice_station());

        etPropertyName.setText(baseBuildBean.getProperty_department());
        etAQZRR.setText(baseBuildBean.getProperty_response_man());
        etAQZRRTel.setText(baseBuildBean.getProperty_response_tel());
        etLXR.setText(baseBuildBean.getProperty_contact_man());
        etLXRTel.setText(baseBuildBean.getProperty_contact_tel());
        etYWH.setText(baseBuildBean.getOwners_committee());
        etYWHZR.setText(baseBuildBean.getCommittee_response_man());
        etYWHZRTel.setText(baseBuildBean.getCommittee_response_tel());
        etYWHLXR.setText(baseBuildBean.getCommittee_contact_man());
        etYWHLXRTel.setText(baseBuildBean.getCommittee_contact_tel());
        etLouZhang.setText(baseBuildBean.getPeer_advisor());
        etLouZhangTel.setText(baseBuildBean.getPeer_advisor_tel());
        if (baseBuildBean.getIs_accept() == 1) {
            isPass.setChecked(true);
        } else
            isNoPass.setChecked(true);
        etWJWH.setText(baseBuildBean.getRecord_number());
        if (baseBuildBean.getNo_edit() == 1) {
            tvSearch.setVisibility(View.VISIBLE);
        } else {
            tvSearch.setVisibility(View.INVISIBLE);
        }

        PicSelectConstans.publish_pics = baseBuildBean.getImage() == null ? new ArrayList<String>()
                : baseBuildBean.getImage();
        refreshAdapter(gvPic);
    }

    private void setViewStatus() {
        // 设置必填项检测提示
        etName.setTag(R.id.tag_view_empty, "建筑名称不能为空");
        etAdress.setTag(R.id.tag_view_empty, "建筑地址不能为空");
        etPolice.setTag(R.id.tag_view_empty, "派出所不能为空");

        rgIsPass.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.isPass) {
                    isPassValue = 1;
                } else isPassValue = 0;
            }
        });
    }


    private void setTop() {
        tvTitle.setText("建筑基础属性");
        tvSearch.setCompoundDrawables(null, null, null, null);
        tvSearch.setText("保存");
    }

    @OnClick({R.id.tvBack, R.id.tvSearch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvBack:
                finish();
                break;
            case R.id.tvSearch:
                // 保存
                if (CheckUtil.checkEditText(etName, etAdress,etPolice)) {
                    if (TextUtils.isEmpty(street) )
                    {
                        ToastUtil.getInstances().showMsg("请选择街道");
                        return;
                    }
                    else if (TextUtils.isEmpty(zone))
                    {
                        ToastUtil.getInstances().showMsg("请选择社区");
                        return;
                    }
                    else
                    {
                        downloadImage();
                    }

                }
                break;

            default:
                break;
        }
    }

    private void doPost() {

        Map<String, String> params = new HashMap<>();
        params.put("name", etName.getText().toString());
        params.put("type", "1");
        params.put("street", street);
        params.put("community", zone);
        params.put("police_station", etPolice.getText().toString());
        params.put("address", etAdress.getText().toString());
        params.put("property_department", etPropertyName.getText().toString());
        params.put("property_response_man", etAQZRR.getText().toString());
        params.put("property_response_tel", etAQZRRTel.getText().toString());
        params.put("property_contact_man", etLXR.getText().toString());
        params.put("property_contact_tel", etLXRTel.getText().toString());
        params.put("owners_committee", etYWH.getText().toString());
        params.put("committee_response_man", etYWHZR.getText().toString());
        params.put("committee_response_tel", etYWHZRTel.getText().toString());
        params.put("committee_contact_man", etYWHLXR.getText().toString());
        params.put("committee_contact_tel", etYWHLXRTel.getText().toString());
        params.put("peer_advisor", etLouZhang.getText().toString());
        params.put("peer_advisor_tel", etLouZhangTel.getText().toString());
        params.put("is_accept", "" + isPassValue);
        params.put("record_number", etWJWH.getText().toString());

        MultipartBody.Builder builder = new MultipartBody.Builder();

        putBody(builder, AppConfig.ACCESS_TOKEN, AppMediaType.TEXT, UserInfoUtil.getCurrentUserAccessToken());
        putBody(builder, "id", AppMediaType.TEXT, build_id);
        putBody(builder, "type", AppMediaType.TEXT, 1 + "");
        putBody(builder, "data", AppMediaType.TEXT, new Gson().toJson(params));


        // 图片数组
        int size = PicSelectConstans.publish_pics.size();
        File file;
        for (int i = 0; i < size; i++) {
            if (PicSelectConstans.publish_pics.get(i).contains("http")) {
                continue;
            }
            file = new File(PicSelectConstans.publish_pics.get(i));
//            postForm.addFile("image[]", "pic" + (i + 1) + ".jpg", file);
            putBody(builder, "image[]", AppMediaType.JPG, file);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();

        HttpMethods.getInstance().postBaseBuildInfo(multipartBody)
                .subscribe(new SampleProgressObserver<BaseBuildBean>(this) {
                    @Override
                    public void onNext(BaseBuildBean baseBuildBean) {
                        Intent intent = new Intent();
                        Log.e(TAG, "onNext: " + baseBuildBean.getBuild_id());
                        intent.putExtra("build_no", baseBuildBean.getBuild_id());
                        setResult(RESULT_OK, intent);
                        finish();

                        ToastUtil.getInstances().showMsg("保存成功");
                    }
                });

//        HttpMethods.getInstance().postBaseBuildInfo(UserInfoUtil.getCurrentUserAccessToken(),build_id,1, new Gson().toJson(params))
//                .subscribe(new SampleProgressObserver<BaseBuildBean>(this) {
//                    @Override
//                    public void onNext(BaseBuildBean o) {
//                        Intent intent = new Intent();
//                        intent.putExtra("build_no", o.getBuild_id());
//                        setResult(RESULT_OK, intent);
//                        finish();
//
//                        ToastUtil.getInstances().showMsg("保存成功");
//                    }
//                });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        PicSelectConstans.publish_pics.clear();
    }

    @Override
    public void post() {
        doPost();
    }


    Map<String, RequestBody> putMap(Map<String, RequestBody> source, String filed, MediaType mediaType, Object value) {
        if (value instanceof String) {
            source.put(filed, RequestBody.create(mediaType, value.toString()));
        } else if (value instanceof File) {
            File file = (File) value;
            source.put(filed + "\";filename=\"" + file.getName(), RequestBody.create(mediaType, file));
        }


        return source;
    }

    MultipartBody.Builder putBody(MultipartBody.Builder source, String filed, MediaType mediaType, Object value) {
        if (value instanceof String) {
            source.addFormDataPart(filed, value.toString());
        } else if (value instanceof File) {
            File file = (File) value;
            source.addFormDataPart(filed, file.getName(), RequestBody.create(mediaType, file));
        }
        return source;
    }

    private void resetFirst()
    {
        street = "";
        streetDataList.clear();
        DataInputStreetBean head = new DataInputStreetBean();
        head.setName("请选择");
        streetDataList.add(head);
    }

    private void resetSecond()
    {
        zone = "";
        zoneDataList.clear();
        DataInputZoneBean head = new DataInputZoneBean();
        head.setName("请选择");
        zoneDataList.add(head);
        spZone.setSelection(0);
    }

    private void setAdapter() {
        resetFirst();
        stateFirstAdapter = new CommonAdapter<DataInputStreetBean>(this, streetDataList, R.layout.item_spinner) {

            @Override
            public void convert(ViewHolder holder, DataInputStreetBean t) {
                holder.setText(R.id.state_name, t.getName());
            }
        };
        spStreet.setAdapter(stateFirstAdapter);
        spStreet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                resetSecond();
                //做个判断，如果上级菜单传给我们的是空id，即上级未选择选项，则我们不去获取下级的菜单
                if (streetDataList.size() >0 && !streetDataList.get(position).getName().equals("请选择")) {
                    getSecond(streetDataList.get(position).getName());
                    street = streetDataList.get(position).getName();
                }
                else
                {
                    stateSecondAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        resetSecond();
        stateSecondAdapter = new CommonAdapter<DataInputZoneBean>(this, zoneDataList, R.layout.item_spinner) {

            @Override
            public void convert(ViewHolder holder, DataInputZoneBean t) {
                holder.setText(R.id.state_name, t.getName());
            }
        };
        spZone.setAdapter(stateSecondAdapter);
        spZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                //做个判断，如果上级菜单传给我们的是空id，即上级未选择选项，则我们不去获取下级的菜单
                if (zoneDataList.size() >0 && !zoneDataList.get(position).getName().equals("请选择")) {
                    zone = zoneDataList.get(position).getName();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /**
     * @author: HYM
     * @Title: getFirst
     * @Description: TODO(得到一级设备的列表)    void
     * @date: 2017-5-11
     */
    private void getFirst()
    {
        HttpMethods.getInstance().getDataInputStreet(UserInfoUtil.getCurrentUserAccessToken()).subscribe(
                new SampleProgressObserver<List<DataInputStreetBean>>(this) {
                    @Override
                    public void onNext(List<DataInputStreetBean> dataInputStreetBeans) {
                        if (dataInputStreetBeans.size() > 0) {
                            streetDataList.addAll(dataInputStreetBeans);
                            stateFirstAdapter.notifyDataSetChanged();
                        }
                    }
                }
        );
    }

    private void getSecond(String streetName)
    {
        HttpMethods.getInstance().getDataInputZone(UserInfoUtil.getCurrentUserAccessToken(),streetName).subscribe(
                new SampleProgressObserver<List<DataInputZoneBean>>(this) {
                    @Override
                    public void onNext(List<DataInputZoneBean> dataInputZoneBean) {
                        if (dataInputZoneBean.size() > 0) {
                            zoneDataList.addAll(dataInputZoneBean);
                            Log.e(TAG, "getSecond: zone  " + zone);
                            if (!TextUtils.isEmpty(firstZone))
                            {
                                spZone.setSelection(getPositionByZoneName(firstZone),true);
                                firstZone ="";
                            }
                            stateSecondAdapter.notifyDataSetChanged();
                        }
                    }
                }
        );
    }

    private int getPositionByStreetName(String street)
    {
        for (int i = 0;i<streetDataList.size();i++)
        {
            if (streetDataList.get(i).getName().equals(street))
            {
                return i;
            }
        }
        return 0;
    }

    private int getPositionByZoneName(String zone)
    {
        for (int i = 0;i<zoneDataList.size();i++)
        {
            if (zoneDataList.get(i).getName().equals(zone))
            {
                return i;
            }
        }
        return 0;
    }
}
